﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace PKS.CustomPages
{
	public class CreateSeriesPage : Microsoft.SharePoint.WebControls.LayoutsPageBase
	{
		#region " Consts "

		private const string ctrlPrefix = "tsc5282FBB87B8F44bfA1B81C2F65F616DE_";
		private Guid titleGuid = new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247");

		#endregion

		#region " Controls "

		//protected Literal debugOutput;
		protected Label lblError;
		protected PlaceHolder ph1;
		protected Button btnOkay1, btnOkay2, btnCancel1, btnCancel2;

		#endregion

		#region " Properties "

		protected string PageTitle
		{ get { return "Create Series"; } }

		protected bool ShowAllFields
		{
			get
			{
				if (Request.QueryString["ShowAllFields"] == null) { return false; }
				try
				{
					bool showAllFields = bool.Parse(Request.QueryString["ShowAllFields"]);
					return showAllFields;
				}
				catch { }
				return false;
			}
		}

		protected string List
		{
			get
			{
				if (string.IsNullOrEmpty(Request.QueryString["List"]))
				{
					return "";
				}
				else
				{
					return HttpUtility.UrlDecode(Request.QueryString["List"]);
				}
			}
		}

		protected string Source
		{
			get
			{
				if (string.IsNullOrEmpty(Request.QueryString["Source"]))
				{
					string r = RootFolder;
					if (string.IsNullOrEmpty(r)) { return "~/"; }
					r = r.Replace("\\", "/");
					if (!r.StartsWith("/")) { r = "/" + r; }
					return r;
				}
				else
				{
					return HttpUtility.UrlDecode(Request.QueryString["Source"]);
				}
			}
		}

		protected string RootFolder
		{
			get
			{
				if (string.IsNullOrEmpty(Request.QueryString["RootFolder"]))
				{
					return "";
				}
				else
				{
					return HttpUtility.UrlDecode(Request.QueryString["RootFolder"]);
				}
			}
		}

		protected string ContentTypeId
		{
			get
			{
				if (string.IsNullOrEmpty(Request.QueryString["ContentTypeId"]))
				{
					return "";
				}
				else
				{
					return HttpUtility.UrlDecode(Request.QueryString["ContentTypeId"]);
				}
			}
		}

		#endregion

		#region " functions "

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			lblError.Text = "";
			//debugOutput.Text = "";
			WritePage();

			btnOkay1.Click += new EventHandler(btnOkay_Click);
			btnOkay2.Click += new EventHandler(btnOkay_Click);
			btnCancel1.Click += new EventHandler(btnCancel_Click);
			btnCancel2.Click += new EventHandler(btnCancel_Click);
		}

		void btnCancel_Click(object sender, EventArgs e)
		{
			RedirectToSource();
		}

		void btnOkay_Click(object sender, EventArgs e)
		{
			CreateItem();
		}

		protected void RedirectToSource()
		{
			Response.Redirect(Source);
		}

		protected string CreateSafeFileName(string f)
		{
			if (string.IsNullOrEmpty(f)) { return ""; }
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < f.Length; i++)
			{
				char c = f[i];
				if (char.IsLetterOrDigit(c))
				{
					sb.Append(c.ToString());
				}
				else
				{
					sb.Append("_");
				}
			}

			return sb.ToString();
		}

		protected void CreateItem()
		{
			EnsureChildControls();
			if (!this.IsValid) { return; }

			SPDocumentLibrary dl = (SPDocumentLibrary)RetrieveList();
			if (dl == null)
			{
				ThrowError("Document Library Not Found: " + RootFolder + " (" + List + ")");
				return;
			}

			SPContentType ct = RetrieveContentType();
			if (ct == null)
			{
				ThrowError("Content Type Not Found: " + ContentTypeId);
				return;
			}

			//////////////////////////////////////////////////////////////////////////////////////////

			SPFile layoutFile = null;
			try
			{
				//_catalogs/masterpage/PSSSeriesLayoutPage.aspx
				SPFolder folder = Web.Folders["_catalogs"].SubFolders["masterpage"];
				foreach (SPFile tfile in folder.Files)
				{
					if (string.Equals(tfile.Name, "PSSSeriesLayoutPage.aspx", StringComparison.InvariantCultureIgnoreCase)
						|| string.Equals(tfile.Name, "PSMSSeriesLayoutPage.aspx", StringComparison.InvariantCultureIgnoreCase)
						|| string.Equals(tfile.Name, "PKSSeriesLayoutPage.aspx", StringComparison.InvariantCultureIgnoreCase)
						|| string.Equals(tfile.Name, "PKS.SeriesLayoutPage.aspx", StringComparison.InvariantCultureIgnoreCase))
					{
						layoutFile = tfile;
						break;
					}
				}
			}
			catch { }

			if (layoutFile == null)
			{
				ThrowError("Could not find \"_catalogs/masterpage/PSSSeriesLayoutPage.aspx\", \"_catalogs/masterpage/PSMSSeriesLayoutPage.aspx\", \"_catalogs/masterpage/PKSSeriesLayoutPage.aspx\", or \"_catalogs/masterpage/PKS.SeriesLayoutPage.aspx\", please ensure that a valid layout file exists.");
				return;
			}

			byte[] content = layoutFile.OpenBinary();

			//////////////////////////////////////////////////////////////////////////////////////////
			string title = "";
			foreach (Control c in ph1.Controls)
			{
				if (c.ID.StartsWith(ctrlPrefix))
				{
					BaseFieldControl bfc = (BaseFieldControl)c;
					foreach (SPField f in ct.Fields)
					{
						if (string.Equals(ctrlPrefix + f.InternalName, c.ID, StringComparison.InvariantCultureIgnoreCase))
						{
							if (f.Id == titleGuid)
							{
								if (bfc.Value == null)
								{
									ThrowError("Please supply a title.");
									return;
								}
								title = bfc.Value.ToString();
							}
						}
					}
				}
			}

			//////////////////////////////////////////////////////////////////////////////////////////
			//// Read a document off the c drive and open a stream
			//FileStream stream = File.OpenRead(@"c:\page.aspx");
			//byte[] content = new byte[stream.Length];

			//// Read the file from the stream into the byte array
			//stream.Read(content, 0, (int)stream.Length);
			//stream.Close();

			////byte[] content = Encoding.UTF8.GetBytes("Hello World");

			// Give the file a name, used as the name of the list
			// item once it gets into the document library
			string fileNameOnceInLibrary = CreateSafeFileName(title) + ".aspx";

			//SPSite mySiteCollection = new SPSite("http://cleanmoss");
			//SPWeb myWeb = mySiteCollection.RootWeb;

			// Get the folder that should store the document
			// In this case, there's a document library called "Docs"
			// within the Root Web of the Site Collection
			SPFolder parent = dl.RootFolder; // Web.Folders["Womp"];
			string[] path = RootFolder.Split('/');
			if ((path != null) && (path.Length > 1))
			{
				for (int i = 1; i < path.Length; i++)
				{
					foreach (SPFolder f in parent.SubFolders)
					{
						if (string.Equals(f.Name, path[i], StringComparison.InvariantCultureIgnoreCase))
						{
							parent = f;
							break;
						}
					}
				}
			}



			// Within the "Docs" library, add the document into
			// a folder called "Folder1"
			//SPFolder child = parent.SubFolders["Folder1"];

			// Add the file to the Files collection and commit to database
			SPFile file = parent.Files.Add(parent.Url + "/" +
				  fileNameOnceInLibrary, content, true);

			parent.Update();
			// This next portion demonstrates modifying meta data
			// on the document that was just uploaded

			//SPDocumentLibrary docs = (SPDocumentLibrary)Web.Lists
			//	  [parent.ContainingDocumentLibrary];

			SPListItem item = dl.Items[file.UniqueId]; // docs.Items[file.UniqueId];
			//item.ContentType = ct;
			//item["Title"] = "Marketing";
			item["ContentTypeId"] = ct.Id;
			//item[new Guid("c042a256-787d-4a6f-8a8a-cf6ab767f12d")] = ct;


			//////////////////////////////////////////////////////////////////////////////////////////////
			//debugOutput.Text = "";
			foreach (Control c in ph1.Controls)
			{
				if (c.ID.StartsWith(ctrlPrefix))
				{
					BaseFieldControl bfc = (BaseFieldControl)c;
					foreach (SPField f in ct.Fields)
					{
						if (string.Equals(ctrlPrefix + f.InternalName, c.ID, StringComparison.InvariantCultureIgnoreCase))
						{
							item[f.Id] = bfc.Value;
							//debugOutput.Text += f.Id.ToString() + " -- ";
							break;
						}
					}

					//debugOutput.Text += c.ID.ToString() + " = \"";
					//if (bfc.Value == null)
					//{
					//    debugOutput.Text += "(null)\"";
					//}
					//else
					//{
					//    debugOutput.Text += bfc.Value.ToString() + "\", ";
					//    debugOutput.Text += bfc.Value.GetType().ToString();
					//}
					//debugOutput.Text += "<br />" + Environment.NewLine;
				}
			}

			//bool oldValue = Web.AllowUnsafeUpdates;
			//try
			//{
			//    Web.AllowUnsafeUpdates = true;
			item.Update();
			//}
			//catch { }
			//finally
			//{
			//    Web.AllowUnsafeUpdates = oldValue;
			//}

			//Throws the back to another page
			RedirectToSource();
		}

		private void ThrowError(string Error)
		{
			lblError.Text = Error;
		}

		protected SPList RetrieveList()
		{
			if (string.IsNullOrEmpty(List)) { return null; }

			Guid listGuid = Guid.Empty;
			if (!string.IsNullOrEmpty(List))
			{
				try
				{
					listGuid = new Guid(List);
				}
				catch
				{
					return null;
				}
			}

			foreach (SPList list in Web.Lists)
			{
				if (list.ID == listGuid && listGuid != Guid.Empty)
				{
					return list;
				}
			}
			return null;
		}

		protected SPContentType RetrieveContentType()
		{
			if (string.IsNullOrEmpty(ContentTypeId)) { return null; }
			SPList docLib = RetrieveList();
			foreach (SPContentType ct in docLib.ContentTypes)
			{
				if (string.Equals(ct.Id.ToString(), ContentTypeId, StringComparison.InvariantCultureIgnoreCase))
				{
					return ct;
				}
			}
			return null;
		}


		protected void Cls()
		{
			EnsureChildControls();
			ph1.Controls.Clear();
		}

		protected void WriteLiteral(string s)
		{
			Literal l = new Literal();
			l.Text = s;
			l.ID = Guid.NewGuid().ToString();
			ph1.Controls.Add(l);
		}

		protected void WriteField(SPField f)
		{
			WriteLiteral("<tr>");
			//WriteLiteral(@"<td nowrap=""true"" valign=""top"" class=""ms-formlabel"">");
			WriteLiteral(@"<td nowrap=""true"" valign=""top"" width=""190px"" class=""ms-formlabel""><h3 class=""ms-standardheader""><nobr>");
			WriteLiteral(f.Title);
			WriteLiteral(@"</nobr></h3></td><td valign=""top"" class=""ms-formbody"">");

			BaseFieldControl c = f.FieldRenderingControl;
			c.ID = ctrlPrefix + f.InternalName.ToString();
			c.ControlMode = SPControlMode.New;
			c.EnableViewState = true;
			ph1.Controls.Add(c);

			WriteLiteral("</td>");
			WriteLiteral("</tr>");
		}

		protected void WriteField(Guid Id, SPFieldCollection fc)
		{
			foreach (SPField f in fc)
			{
				if (f.Id == Id) { WriteField(f); return; }
			}
			throw new Exception("Field not found: " + Id.ToString());
		}

		protected void WritePage()
		{
			Cls();
			SPList docLib = RetrieveList();
			if (docLib == null)
			{
				ThrowError("Document Library Not Found: " + RootFolder + " (" + List + ")");
				return;
			}

			SPContentType ct = RetrieveContentType();
			if (ct == null)
			{
				ThrowError("Content Type Not Found: " + ContentTypeId);
				return;
			}

			List<Guid> hiddenFields = new List<Guid>();
			hiddenFields.Add(titleGuid);
			hiddenFields.Add(new Guid("c042a256-787d-4a6f-8a8a-cf6ab767f12d")); //Content Type
			hiddenFields.Add(new Guid("8553196d-ec8d-4564-9861-3dbe931050c8")); //Name?

			/*hiddenFields.Add(new Guid("51d39414-03dc-4bd0-b777-d3e20cb350f7")); //Scheduling Start Date
			hiddenFields.Add(new Guid("a990e64f-faa3-49c1-aafa-885fda79de62")); //Scheduling End Date
			hiddenFields.Add(new Guid("543bc2cf-1f30-488e-8f25-6fe3b689d9ac")); //Roll-up Image
			hiddenFields.Add(new Guid("dc47d55f-9bf9-494a-8d5b-e619214dd19a")); //Contact Picture*/

			//WriteLiteral("<table border='1'>");
			WriteLiteral(@"<table class=""ms-formtable"" style=""margin-top: 8px;"" border=0 cellpadding=0 id=""formTbl"" cellspacing=0 width=100%>");
			WriteField(titleGuid, ct.Fields);

			bool showAllFields = ShowAllFields; //cache the value for the duration of the for loop
			foreach (SPField f in ct.Fields)
			{
				if ((!f.ReadOnlyField) && (!f.Hidden) && (!hiddenFields.Contains(f.Id))
					&& (((f.ShowInNewForm.HasValue) && (f.ShowInNewForm.Value)) || showAllFields || f.Required))
				{
					WriteField(f);
				}
			}
			WriteLiteral("</table>");
		}

		#endregion
	}
}